﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.IoUtils;
using CatUtils.Utils.Enhance.ThreadTool;
using CatUtils.Utils.SpecialUtils.Html;
using CatUtils.Utils.SpecialUtils.PicBed.Smms;
using CatUtils.Utils.SpecialUtils.View;
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace CatUtils.Utils.SpecialUtils.PicBed.Sina
{
    public partial class SinaLoginForm : Form
    {
        private static string UserName = "";
        private static string UserPass = "";

        public SinaLoginForm(string OpenLink)
        {
            InitializeComponent();
            if (OpenLink != "")
                webBrowser1.Navigate(OpenLink);
            string UserInfo = FileHelper.ReadAllText(SinaStaticvalue.UserFilePath);
            UserName = HtmlHelper.GetFirstText(UserInfo, "//username");
            UserPass = HtmlHelper.GetFirstText(UserInfo, "//userpass");
        }

        private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            try
            {
                Console.WriteLine(webBrowser1.DocumentTitle);
                bool PassFlag = false;//是否已经自动输入了密码
                foreach (HtmlElement links in this.webBrowser1.Document.Links)
                {
                    links.SetAttribute("target", "_self");
                }
                foreach (HtmlElement form in this.webBrowser1.Document.Forms)
                {
                    form.SetAttribute("target", "_self");
                }
                if (webBrowser1.DocumentTitle == "导航已取消" || webBrowser1.DocumentTitle == "无法显示此页")
                {
                    Console.WriteLine("判断网络连接出现问题，休眠后重启转向。");
                    ThreadSleep.SetSecondClock(SinaStaticvalue.ReloadSleepTime);
                    webBrowser1.Navigate("https://weibo.com/");
                }

                if ((webBrowser1.DocumentTitle == "微博-随时随地发现新鲜事" || webBrowser1.DocumentTitle == "微博焦點 - 微博香港站" || webBrowser1.DocumentTitle == "微博北美站")
                    && UserPass != "" && UserName != "")
                {
                    Console.WriteLine("尚未登录");
                    webBrowser1.Document.GetElementById("loginname").InnerText = UserName;
                    foreach (HtmlElement item in webBrowser1.Document.GetElementsByTagName("input"))
                    {
                        string Classname = item.GetAttribute("className").Trim();
                        if (Classname == "")
                            continue;

                        if (Classname == "W_input" && item.GetAttribute("type") == "password")
                        {
                            // item.SetAttribute("value", UserPass);
                            PassFlag = true;
                        }
                    }
                    if (PassFlag)
                        foreach (HtmlElement item in webBrowser1.Document.GetElementsByTagName("a"))
                        {
                            string Classname = item.GetAttribute("className");

                            if (Classname == "W_btn_a btn_32px")
                            {
                                /*
                                if (!checkBox2.Checked)
                                    StartLogin(item);
                                else
                                    Console.WriteLine("已取消自动登录");*/
                            }
                        }
                }
                if (webBrowser1.DocumentTitle.IndexOf("首页") >= 0)
                {
                    CookiesSave();
                }
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
        }

        private static int ClickCount = 0;
        /*
        private void StartLogin(HtmlElement item)
        {
            Console.WriteLine("可以登录！");

            if (ClickCount++ % 3 == 0)
            {
                Console.WriteLine("模拟点击已取消");
                Console.WriteLine("模拟点击" + ClickCount);
                //   item.InvokeMember("click");
            }
        }*/

        private void CookiesSave()
        {
            SinaImgUploadTool.LoginFormFlag = false;
            Console.WriteLine("更新cookies，关闭页面");
            FileHelper.WriteText(SinaStaticvalue.CookiesFile, GetCookiestring("https://weibo.com"));

            if (checkBox1.Checked) this.Dispose();
        }

        [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern bool InternetGetCookieEx(string pchURL, string pchCookieName, StringBuilder pchCookieData, ref int pcchCookieData, int dwFlags, object lpReserved);

        //取出Cookie，当登录后才能取
        private static string GetCookiestring(string url)
        {
            // Determine the size of the cookie
            int datasize = 256;
            StringBuilder cookieData = new StringBuilder(datasize);
            try
            {
                if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, null))
                {
                    if (datasize < 0)
                        return null;
                    // Allocate StringBuilder large enough to hold the cookie
                    cookieData = new StringBuilder(datasize);
                    if (!InternetGetCookieEx(url, null, cookieData, ref datasize, 0x00002000, null))
                        return null;
                }
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
            return cookieData.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageHelper.Alert(GetCookiestring("http://picupload.service.weibo.com"));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("http://picupload.service.weibo.com/interface/pic_upload.php");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("https://weibo.com/");
        }

        private void button4_Click(object sender, EventArgs e)
        {
            CookiesSave();
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
        }

        private void SinaLoginForm_Shown(object sender, EventArgs e)
        {
            Console.WriteLine("第一次显示窗口");
            webBrowser1.Navigate("https://weibo.com/");
        }
    }
}